package stark.app.function.novelcreator;

import android.graphics.drawable.Drawable;
import android.util.Log;

import com.blankj.utilcode.util.FileIOUtils;
import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.stark.novelcreator.lib.model.BookDbHelper;
import com.stark.novelcreator.lib.model.BookshelfManager;
import com.stark.novelcreator.lib.model.bean.Book;
import com.stark.novelcreator.lib.model.bean.Bookshelf;
import com.stark.novelreader.ReaderEntry;

import java.util.ArrayList;
import java.util.List;

import androidx.lifecycle.Observer;
import io.reactivex.rxjava3.core.ObservableEmitter;
import stark.app.R;
import stark.app.databinding.ActivityNovelCreateDemoBinding;
import stark.common.basic.base.BaseNoModelActivity;
import stark.common.basic.utils.FileUtil;
import stark.common.basic.utils.RxUtil;

/**
 * Author：daizhongbin on 2022/12/5
 * Email：1027154338@qq.com
 * Desc:
 */
public class NovelCreatorDemoActivity extends BaseNoModelActivity<ActivityNovelCreateDemoBinding> {

    @Override
    protected int onCreate() {
        return R.layout.activity_novel_create_demo;
    }

    @Override
    protected void initView() {
        mDataBinding.btnAddDefType.setOnClickListener(v -> {
            addDefType();
        });
        mDataBinding.btnGetDefType.setOnClickListener(v -> {
            getDefType();
        });
        mDataBinding.btnAddCustomType.setOnClickListener(v -> {
            addCustomType();
        });
        mDataBinding.btnGetCustomType.setOnClickListener(v -> {
            getCustomType();
        });
        mDataBinding.btnModType.setOnClickListener(v -> {
            updateCustomBookshelf();
        });
        mDataBinding.btnDelType.setOnClickListener(v -> {
            delCustomBookshelf();
        });
        mDataBinding.btnAddBook.setOnClickListener(v -> {
            addBook();
        });
        mDataBinding.btnCreateBook.setOnClickListener(v -> {
            createBook();
        });
        mDataBinding.btnUpdateBook.setOnClickListener(v -> {
            updateBook();
        });
        mDataBinding.btnDelBook.setOnClickListener(v -> {
            delBook();
        });
        mDataBinding.btnGetBookByType.setOnClickListener(v -> {
            getBookByType();
        });
    }

    @Override
    protected void initData() {
    }

    private void addDefType() {
        List<Bookshelf> bookshelfList = new ArrayList<>();
        Bookshelf bookshelf = Bookshelf.createBookShelf("武侠", R.drawable.ic_launcher);
        bookshelfList.add(bookshelf);
        bookshelf = Bookshelf.createBookShelf("言情", R.drawable.ic_launcher);
        bookshelfList.add(bookshelf);
        bookshelf = Bookshelf.createBookShelf("动作", R.drawable.ic_launcher);
        bookshelfList.add(bookshelf);

        BookshelfManager.getInstance().addDefBookshelves(bookshelfList);
    }

    private void getDefType() {
        List<Bookshelf> bookshelfList = BookshelfManager.getInstance().getDefBookshelves();
        updateRet(GsonUtils.toJson(bookshelfList));
        if (bookshelfList != null && bookshelfList.size() > 0) {
            Bookshelf bookshelf = bookshelfList.get(0);
            Drawable drawable = getResources().getDrawable(bookshelf.getImgId());
            Log.e("dzb", "getDefType: drawable = " + drawable);
        }
    }

    private void addCustomType() {
        //下面“封面图片路径”这里只是做个示范
        String name = "自定义分类_" + System.currentTimeMillis();
        Bookshelf bookshelf = Bookshelf.createBookShelf(name, "封面图片路径");
        BookshelfManager.getInstance().addCustomBookshelf(bookshelf);
    }

    private void getCustomType() {
        List<Bookshelf> bookshelfList = BookshelfManager.getInstance().getCustomBookshelves();
        updateRet(GsonUtils.toJson(bookshelfList));
    }

    private void updateCustomBookshelf() {
        List<Bookshelf> bookshelfList = BookshelfManager.getInstance().getCustomBookshelves();
        if (bookshelfList == null || bookshelfList.size() == 0) {
            ToastUtils.showShort("请先添加自定义分类");
            return;
        }
        Bookshelf bookshelf = bookshelfList.get(0);
        bookshelf.setName(bookshelf.getName() + "_改书架名称");
        BookshelfManager.getInstance().updateBookshelf(bookshelf);
        updateRet(GsonUtils.toJson(bookshelf));
    }

    private void delCustomBookshelf() {
        List<Bookshelf> bookshelfList = BookshelfManager.getInstance().getCustomBookshelves();
        if (bookshelfList == null || bookshelfList.size() == 0) {
            return;
        }
        BookshelfManager.getInstance().delBookshelf(bookshelfList.get(0));
    }

    private void addBook() {
        Book book = new Book();
        book.name = "书名";
        book.author = "作者";
        //简介也可以从书籍内容中截取前面的一些字符作为简介
        book.shortDesc = "简介";
        book.imgPath = "书本封面图片所在的文件路径";
        book.filePath = "书本内容所在的文件路径";
        book.createTime = System.currentTimeMillis();
        //添加书所属的类型
        List<Bookshelf> bookshelfList = BookshelfManager.getInstance().getAllBookshelves();
        if (bookshelfList == null || bookshelfList.size() == 0) {
            ToastUtils.showShort("请先添加书架即类型");
            return;
        }
        //添加所属书架（类型），可调用多次添加多个
        book.addType(bookshelfList.get(0).getId());

        BookDbHelper.insert(book);
        updateRet(GsonUtils.toJson(book));
    }

    private void createBook() {
        String content = "这是小说的内容。";
        Book book = new Book();
        book.name = "书名";
        book.author = "作者";
        //简介:可用户输入或者取内容的前面X个字符串作为简介
        book.shortDesc = "简介";
        //book.shortDesc = content.substring(0, Math.min(10, content.length()));
        book.imgPath = "封面图片路径";
        book.createTime = System.currentTimeMillis();
        showDialog("保存中...");
        //将内容保存到文件中去
        RxUtil.create(new RxUtil.Callback<Boolean>() {
            @Override
            public void doBackground(ObservableEmitter<Boolean> emitter) {
                String filePath = FileUtil.generateFilePathByName("novel", book.name + ".txt");
                boolean ret = FileIOUtils.writeFileFromString(filePath, content);
                if (ret) {
                    book.filePath = filePath;
                    BookDbHelper.insert(book);
                }
                emitter.onNext(ret);
            }

            @Override
            public void accept(Boolean ret) {
                dismissDialog();
                ToastUtils.showShort(ret ? "保存成功" : "保存失败");
                updateRet(GsonUtils.toJson(book));
            }
        });

    }

    private void updateBook() {
        List<Book> books = BookDbHelper.getAll();
        if (books == null || books.size() == 0) {
            return;
        }
        Book book = books.get(0);
        book.name = "更改书名";
        book.shortDesc = "更改简介";
        showDialog("更新中...");
        RxUtil.create(new RxUtil.Callback<Boolean>() {
            @Override
            public void doBackground(ObservableEmitter<Boolean> emitter) {
                String content = FileIOUtils.readFile2String(book.filePath);
                content += "添加更改的内容";
                boolean ret = FileIOUtils.writeFileFromString(book.filePath, content);
                if (ret) {
                    BookDbHelper.update(book);
                }
                emitter.onNext(ret);
            }

            @Override
            public void accept(Boolean ret) {
                dismissDialog();
                ToastUtils.showShort(ret ? "更新成功" : "更新失败");
                updateRet(GsonUtils.toJson(book));
            }
        });
    }

    private void delBook() {
        List<Book> books = BookDbHelper.getAll();
        if (books == null || books.size() == 0) {
            return;
        }
        BookDbHelper.del(books.get(0));
    }

    private void getBookByType() {
        List<Bookshelf> bookshelfList = BookshelfManager.getInstance().getAllBookshelves();
        if (bookshelfList == null || bookshelfList.size() == 0) {
            return;
        }
        BookDbHelper.getBooksByTypeForLiveData(bookshelfList.get(0).getId()).observe(this, new Observer<List<Book>>() {
            @Override
            public void onChanged(List<Book> books) {
                updateRet(GsonUtils.toJson(books));
            }
        });
    }


    private void readBook() {

        ReaderEntry.readFile(this, null);
    }

    private void updateRet(String text) {
        mDataBinding.tvRet.setText("结果：\n" + text);
    }
}
